package flex.cc.e2.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.DigestUtils;

import com.alibaba.druid.support.json.JSONUtils;

public class HttpUtil {
	private static final String e2clientSecret = "test_e2c_2aeeed764adf485985cc5f700f9a352c";
	private static final String e2clientid = "10069";
	private static final Logger logger= LoggerFactory.getLogger(HttpUtil.class);
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String httpUrl = "https://teste2api.test.xdf.cn/E2Api/VerifyE2MF";
		Map reqForm = new HashMap();
		reqForm.put("ip", "127.0.0.1");
		reqForm.put("userAgent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36");
		reqForm.put("e2e", "685650C912BE70E7A107B9FDCC9BFEEE");
		reqForm.put("e2mf", "ff76898e94f9431c9ad5a6554cb0c935");
		reqForm.put("e2clientid", e2clientid);
		Date date = new Date(System.currentTimeMillis());
		String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		time = time.replace(" ", "T");
		System.out.println(time);
		reqForm.put("time", time);
		reqForm.put("sign", getSign(reqForm));
		String resJson = doPostForm(httpUrl, reqForm);
		// 返回：{"status":1,"data":{"email":"t_t1@xdf.cn","e2uid":"d846d3ab-7317-4baf-b8d1-ad050131bae7","u2uid":"d846d3ab-7317-4baf-b8d1-ad050131bae7","nickName":"t_t1","expireTime":"2021-08-10T13:17:43"},"msg":"ok"}
		System.out.println("返回：" + resJson);
	}
	
	/**
     * 生成校验码
     * @param e2e
     * @param e2mf
     * @param ip
     * @param e2clientid
     * @param time
     * @return
     */
    public static String getSign(Map reqForm) {
    	String e2e = reqForm.get("e2e").toString();
    	String e2mf = reqForm.get("e2mf").toString();
    	String ip = reqForm.get("ip").toString();
    	String time = reqForm.get("time").toString();
		String signText = ("VerifyE2MF" + e2e + e2mf + ip + e2clientid + time + e2clientSecret).toLowerCase();
		System.out.println(signText);
		String sign = DigestUtils.md5DigestAsHex(signText.getBytes()).toUpperCase();
		System.out.println(sign);
		return sign;
	}
	
	/**
    * 调用指定接口
    * @param httpUrl : 请求的url
    * @param param : form表单的参数（key,value形式）
    * @return
    */
	public static String doPostForm(String httpUrl, Map param) {
       HttpURLConnection connection = null;
       InputStream is = null;
       OutputStream os = null;
       BufferedReader br = null;
       String result = null;
       try {
           URL url = new URL(httpUrl);
           // 通过远程url连接对象打开连接
           connection = (HttpURLConnection) url.openConnection();
           // 设置连接请求方式
           connection.setRequestMethod("POST");
           // 设置连接主机服务器超时时间：15000毫秒
           connection.setConnectTimeout(15000);
           // 设置读取主机服务器返回数据超时时间：60000毫秒
           connection.setReadTimeout(60000);

           // 默认值为：false，当向远程服务器传送数据/写数据时，需要设置为true
           connection.setDoOutput(true);
           // 默认值为：true，当前向远程服务读取数据时，设置为true，该参数可有可无
           connection.setDoInput(true);
           // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
           connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
           // 设置鉴权信息：Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
           //connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
           // 通过连接对象获取一个输出流
           os = connection.getOutputStream();
           // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的(form表单形式的参数实质也是key,value值的拼接，类似于get请求参数的拼接)
           os.write(createLinkString(param).getBytes());
           // 通过连接对象获取一个输入流，向远程读取
           if (connection.getResponseCode() == 200) {

               is = connection.getInputStream();
               // 对输入流对象进行包装:charset根据工作项目组的要求来设置
               br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

               StringBuffer sbf = new StringBuffer();
               String temp = null;
               // 循环遍历一行一行读取数据
               while ((temp = br.readLine()) != null) {
                   sbf.append(temp);
                   sbf.append("\r\n");
               }
               result = sbf.toString();
           }
       } catch (MalformedURLException e) {
           e.printStackTrace();
       } catch (IOException e) {
           e.printStackTrace();
       } finally {
           // 关闭资源
           if (null != br) {
               try {
                   br.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
           if (null != os) {
               try {
                   os.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
           if (null != is) {
               try {
                   is.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
           // 断开与远程地址url的连接
           connection.disconnect();
       }
       return result;
   }
   
   /**
    * 把数组所有元素排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
    * @param params 需要排序并参与字符拼接的参数组
    * @return 拼接后字符串
    */
   public static String createLinkString(Map<String, String> params) {
       List<String> keys = new ArrayList<String>(params.keySet());
       Collections.sort(keys);
       StringBuilder prestr = new StringBuilder();
       for (int i = 0; i < keys.size(); i++) {
           String key = keys.get(i);
           String value = params.get(key);
           if (i == keys.size() - 1) {// 拼接时，不包括最后一个&字符
               prestr.append(key).append("=").append(value);
           } else {
               prestr.append(key).append("=").append(value).append("&");
           }
       }
       return prestr.toString();
   }
   
   
	/**
    * 调用指定接口
    * @param httpUrl : 请求的url
    * @param param : xml
    * @return
    */
	public static String doPostXML(String httpUrl, Map param) {
		
		logger.info("httpUrl-------"+httpUrl);
       HttpURLConnection connection = null;
       InputStream is = null;
       OutputStream os = null;
       BufferedReader br = null;
       String result = null;
       try {
    	   logger.info("-----------11111-------");
           URL url = new URL(httpUrl);
           logger.info("-----------22222-------");
           // 通过远程url连接对象打开连接
           connection = (HttpURLConnection) url.openConnection();
           logger.info("-----------33333-------");
           // 设置连接请求方式
           connection.setRequestMethod("POST");
           logger.info("-----------44444-------");
           // 设置连接主机服务器超时时间：15000毫秒
           connection.setConnectTimeout(15000);
           logger.info("-----------55555-------");
           // 设置读取主机服务器返回数据超时时间：60000毫秒
           connection.setReadTimeout(60000);
           logger.info("-----------66666-------");
           // 默认值为：false，当向远程服务器传送数据/写数据时，需要设置为true
           connection.setDoOutput(true);
           logger.info("-----------77777-------");
           // 默认值为：true，当前向远程服务读取数据时，设置为true，该参数可有可无
           connection.setDoInput(true);
           logger.info("-----------88888-------");
           // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
           connection.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
           logger.info("-----------99999-------");
           // 设置鉴权信息：Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
           //connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
           // 通过连接对象获取一个输出流
           os = connection.getOutputStream();
           logger.info("-----------10101010101-------");
           // 生成请求体xml
           String soapXml = getSoapXml(param);
           
           logger.info("soapXml-------"+soapXml);
           // 通过输出流对象将参数写出去/传输出去
           os.write(soapXml.getBytes());
           // 通过连接对象获取一个输入流，向远程读取
           logger.info("ResponseCode-------"+connection.getResponseCode());
           if (connection.getResponseCode() == 200) {

               is = connection.getInputStream();
               // 对输入流对象进行包装:charset根据工作项目组的要求来设置
               br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

               StringBuffer sbf = new StringBuffer();
               String temp = null;
               // 循环遍历一行一行读取数据
               while ((temp = br.readLine()) != null) {
                   sbf.append(temp);
                   sbf.append("\r\n");
               }
               result = sbf.toString();
               logger.info("result-------"+result);
               Pattern p = Pattern.compile("<return>(.*?)</return>"); 
               Matcher m = p.matcher(result); 
               String resultJson = "";
               while(m.find()){
            	   resultJson = m.group(1); 
               }
               logger.info("resultJson-------"+resultJson);
               return resultJson;
           }
       } catch (MalformedURLException e) {
           e.printStackTrace();
       } catch (IOException e) {
           e.printStackTrace();
       } finally {
           // 关闭资源
           if (null != br) {
               try {
                   br.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
           if (null != os) {
               try {
                   os.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
           if (null != is) {
               try {
                   is.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
           // 断开与远程地址url的连接
           connection.disconnect();
       }
       return result;
   }
	
	public static String getSoapXml(Map param){
		logger.info("param------------"+param);
		String jsonStr = JSONUtils.toJSONString(param);
		logger.info("jsonStr------------"+jsonStr);
		String soapXml = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:cic=\"http://service.interfacemodule.cic.com/\">"
					+ "<soapenv:Body>"
						+ "<cic:statusWriteBack>"
							+ "<jsonString>"+jsonStr+"</jsonString>"
						+ "</cic:statusWriteBack>"
					+ "</soapenv:Body>"
				+ "</soapenv:Envelope>";
		logger.info("soapXml------------"+soapXml);
		return soapXml;
	}
}
